package com.zsc.springcloud;


import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@Deprecated
public class AccessLimiter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> redisScript;

    /**
     * 限流方法
     *
     * @param key 限流key
     * @param limit 1s中放行limit个凭证
     */
    public void limitAccess(String key,Integer limit){
        // 1.设置lua脚本
        boolean acquired = stringRedisTemplate.execute(
                redisScript,
                Lists.newArrayList(key),
                limit.toString()
        );
        // 脚本返回false,则返回异常
        if (!acquired){
            log.error("your access is blocked,key={}",key);
            throw new RuntimeException("your access is blocked");
        }
    }
}
